package com.stanwind.netty.core;

import com.alibaba.fastjson.JSONObject;
import com.stanwind.netty.api.Log;
import com.stanwind.netty.api.RedisUtils;
import com.stanwind.netty.constant.ServerSetting;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by StanWind on 2017/2/16.
 */
@Service("bootstrapServer")
public class BootstrapServer implements ServerSetting {
    @Autowired
    private Log log;

    @Autowired
    private ServerInitializer serverInitializer;

    @Autowired
    private RedisUtils redisUtils;

    @PostConstruct
    public void serverStart() throws InterruptedException {
        ExecutorService bossGroup = Executors.newCachedThreadPool();
        ExecutorService workerGroup = Executors.newCachedThreadPool();
        try {
            // Build BootstrapServer Class
            ServerBootstrap bootstrap = new ServerBootstrap();

            // Set NIO Socket Factory
            bootstrap.setFactory(new NioServerSocketChannelFactory(bossGroup, workerGroup));

//        // IdelState Timer
//        final HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();

            // Set NIO Channel Factory
            bootstrap.setPipelineFactory(serverInitializer);


            // Bind Port
            bootstrap.bind(new InetSocketAddress(SERVER_PORT));

            log.getLogger().info("WorldChannel run on [" + SERVER_PORT + "]");

            //TODO 在redis上注册服务器
            //regServer(1);   //正常开启
        } finally {
            //bossGroup.shutdown();
            //workerGroup.shutdown();
        }
    }

    @PreDestroy
    public void changeServerState(){
        regServer(0);
    }

    private String currentName;

    private void regServer(int state) {
        Jedis jedis = redisUtils.getJedisObject();

        //生成下个服务器名
        currentName = SERVER_NAME_PRE+SERVER_NAME_ID;
        //写入redis注册本服务器
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ip", SERVER_IP);
        jsonObject.put("port", SERVER_PORT);
        jsonObject.put("state", state);
        jedis.set(currentName, jsonObject.toJSONString());
        redisUtils.recycleJedisOjbect(jedis);
    }
}
